<script setup lang="ts">
import { h, ref } from 'vue';

import { useVbenModal, z } from '@vben/common-ui';

import { useClipboard } from '@vueuse/core';
import { Button, message } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import { querySelectTableApi } from '#/api';
import {
  sysParamsAddApi,
  sysParamsEditApi,
  sysParamsQueryByIdApi,
} from '#/api/system/params';
import { queryDictOptionsApi } from '#/utils';
import { asyncValidDataApi } from '#/utils/handle/async-rules';
import {
  ConfigComponentTypeList,
  ConfigFormItemClassList,
} from '#/views/system/params/params.data';

const { copy } = useClipboard({ legacy: true });

const ExampleFormat =
  '[\n' +
  '  {\n' +
  '    "label": "示例标题1",\n' +
  '    "value": "示例值1"\n' +
  '  },\n' +
  '  {\n' +
  '    "label": "示例标题2",\n' +
  '    "value": "示例值2"\n' +
  '  }\n' +
  ']';

const record = ref({});
const [Form, formApi] = useVbenForm({
  layout: 'horizontal',
  wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-2',
  showDefaultActions: false,
  commonConfig: {
    colon: true,
    labelWidth: 100,
    componentProps: {
      class: 'w-full',
    },
  },
  schema: [
    {
      component: 'ApiSelect',
      label: '类型',
      fieldName: 'typeId',
      formItemClass: 'col-span-2',
      rules: 'required',
      componentProps: {
        placeholder: '请选择类型',
        api: querySelectTableApi,
        params: {
          tableName: 'sys_params_type',
          labelField: 'belong_key_title',
          valueField: 'id',
          sqlSelect: 'del_flag = 0',
        },
      },
    },
    {
      component: 'Input',
      label: '名称',
      fieldName: 'configName',
      componentProps: {
        placeholder: '请输入配置项名称',
      },
      rules: z
        .string()
        .min(2, '配置项名称至少2个字符')
        .max(30, '配置项名称最多30个字符'),
    },
    {
      component: 'Input',
      label: '字段',
      fieldName: 'configField',
      help: '只能包含数字、字母且数字不能开头',
      componentProps: {
        placeholder: '请输入配置项字段',
      },
      dependencies: {
        rules(values, formApi) {
          const rowId = formApi.values?.id;
          return asyncValidDataApi(
            z
              .string({ required_error: '请输入字段' })
              .min(3, '字段至少3个字符')
              .regex(/^[a-z][a-z\d]*$/i, {
                message: '只能包含字母和数字，且不能以数字开头',
              }),
            {
              tableName: 'sys_params',
              fieldName: 'config_field',
              rowId,
            },
          );
        },
        triggerFields: ['configField'],
      },
    },
    {
      component: 'Select',
      label: '组件类型',
      defaultValue: 'Input',
      fieldName: 'configComponentType',
      formItemClass: 'col-span-2',
      componentProps: {
        options: ConfigComponentTypeList,
        placeholder: '请输入组件类型',
      },
      rules: 'required',
    },
    {
      component: 'Textarea',
      label: '组件数据',
      fieldName: 'configComponentData',
      formItemClass: 'col-span-2',
      help: 'JSON格式的数据,否则渲染不出数据!可点击Copy复制基础格式~',
      componentProps: {
        placeholder: '请输入组件数据',
      },
      suffix: () =>
        h(
          Button,
          {
            size: 'small',
            type: 'primary',
            danger: true,
            onClick: () => copy(ExampleFormat),
          },
          () => 'Copy',
        ),
      rules: 'required',
      dependencies: {
        show(values) {
          return (
            values.configComponentType === 'Select' ||
            values.configComponentType === 'RadioGroup' ||
            values.configComponentType === 'CheckboxGroup'
          );
        },
        triggerFields: ['configComponentType'],
      },
    },
    {
      component: 'ApiRadioGroup',
      label: '是否必填',
      defaultValue: 1,
      fieldName: 'configRulesRequired',
      componentProps: {
        buttonStyle: 'solid',
        optionType: 'button',
        afterFetch: (data) => {
          return data.map((item: any) => ({
            label: item.itemText,
            value: Number.parseInt(item.itemVal),
          }));
        },
        api: queryDictOptionsApi,
        params: {
          dictCode: 'yes_or_no',
        },
      },
      rules: 'required',
    },
    // {
    //   component: 'Textarea',
    //   label: '自定义校验规则',
    //   fieldName: 'configRules',
    //   componentProps: {
    //     placeholder: '请输入自定义校验规则',
    //   },
    // },
    // {
    //   component: 'Input',
    //   label: '输入的值',
    //   fieldName: 'inputVal',
    //   componentProps: {
    //     placeholder: '请输入输入的值',
    //   },
    // },
    {
      component: 'ApiRadioGroup',
      label: '禁用',
      defaultValue: 1,
      fieldName: 'isDisabled',
      componentProps: {
        buttonStyle: 'solid',
        optionType: 'button',
        afterFetch: (data) => {
          return data.map((item: any) => ({
            label: item.itemText,
            value: Number.parseInt(item.itemVal),
          }));
        },
        api: queryDictOptionsApi,
        params: {
          dictCode: 'yes_or_no',
        },
      },
      rules: 'required',
    },
    {
      component: 'ApiRadioGroup',
      label: '动态显示',
      defaultValue: 1,
      fieldName: 'isDynamicDisplay',
      formItemClass: 'col-span-2',
      componentProps: {
        buttonStyle: 'solid',
        optionType: 'button',
        afterFetch: (data) => {
          return data.map((item: any) => ({
            label: item.itemText,
            value: Number.parseInt(item.itemVal),
          }));
        },
        api: queryDictOptionsApi,
        params: {
          dictCode: 'yes_or_no',
        },
      },
      rules: 'required',
    },
    {
      component: 'ApiSelect',
      label: 'if字段',
      fieldName: 'dynamicDisplayFields',
      help: '选择动态条件字段,注意：只有当选择的这个字段值相等时,才会显示',
      componentProps: {
        api: querySelectTableApi,
        params: {
          tableName: 'sys_params',
          labelField: 'config_name',
          valueField: 'id',
          sqlSelect: 'del_flag = 0',
        },
        allowClear: true,
        placeholder: '请选择动态显示的字段',
      },
      rules: 'required',
      dependencies: {
        show(values) {
          return values.isDynamicDisplay === 0;
        },
        triggerFields: ['isDynamicDisplay'],
      },
    },
    {
      component: 'Input',
      label: 'if数据',
      fieldName: 'dynamicDisplayVals',
      help: '选择条件字段值,注意：只有当选择的这个字段值和本值相等时,才会显示',
      componentProps: {
        placeholder: '请输入动态显示的数据',
      },
      rules: 'required',
      dependencies: {
        show(values) {
          return values.isDynamicDisplay === 0;
        },
        triggerFields: ['isDynamicDisplay'],
      },
    },
    {
      component: 'Textarea',
      label: '帮助信息',
      fieldName: 'configHelp',
      help: '帮助信息会显示在这里...',
      formItemClass: 'col-span-2',
      componentProps: {
        placeholder: '请输入帮助信息',
      },
    },
    {
      component: 'RadioGroup',
      label: '栅格布局',
      defaultValue: 'col-span-2',
      fieldName: 'configFormItemClass',
      componentProps: {
        buttonStyle: 'solid',
        optionType: 'button',
        options: ConfigFormItemClassList,
        placeholder: '请输入表单项栅格布局',
      },
    },
    {
      component: 'Input',
      label: '排序',
      fieldName: 'sortRank',
      componentProps: {
        placeholder: '请输入排序',
      },
    },
  ],
});

const [Modal, modalApi] = useVbenModal({
  title: 'Modal',
  onCancel: () => {
    modalApi.close();
  },
  onConfirm: onSubmit,
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      record.value = modalApi.getData<Record<string, any>>();
      modalApi.setState({
        title: `${record.value.id ? '编辑' : '新增'}系统参数配置`,
      });
      if (record.value.id) {
        initFun();
      } else {
        formApi.setFieldValue('typeId', record.value.typeId);
      }
    }
  },
});

async function initFun() {
  const res = await sysParamsQueryByIdApi({ id: record.value.id });
  await formApi.setValues(res, false);
}
async function onSubmit() {
  const { valid } = await formApi.validate();
  const values = await formApi.getValues();
  if (valid) {
    if (record.value.id) {
      const msg = await sysParamsEditApi(values);
      message.success(msg);
      await modalApi.close();
    } else {
      const msg = await sysParamsAddApi(values);
      message.success(msg);
      await modalApi.close();
    }
  }
}
</script>

<template>
  <Modal>
    <Form />
  </Modal>
</template>
